package io.github.gaisad.amweb2;

import day240904.MyDBUtil;
import io.github.gaisad.amweb2.pojo.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/users")
public class UsersServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("title", "用户管理");

        List<User> users = new ArrayList<>();
        // 查询数据库中用户表的所有用户信息
        //String sql = "select * from user";
        //String sql = "select id, name, email, password from user";
        // LIMIT {[offset,] row_count | row_count OFFSET offset}
        //String sql = "select id, name, email from user limit 5";
        // LIMIT row_count is equivalent to LIMIT 0, row_count// 第1页
        //String sql = "select id, name, email from user limit 0, 5";
        // 第2页
        //String sql = "select id, name, email from user limit 5, 5";
        // 第3页
        //String sql = "select id, name, email from user limit 10, 5";
        // 动态计算分页需要用到的 offset 和 row_count 之间的关系
        // 假设 row_count = 5，即：每页显示 5 条
        // 那么 offset:
        // -------- 第1页：0，当前页码 (1 - 1) * row_count = 0
        // -------- 第2页：5，当前页码 (2 - 1) * row_count = 1 * 5 = 5
        // -------- 第3页：10，当前页码 (3 - 1) * row_count = 2 * 5 = 10
        int page = 1;
        String pageFromRequest = req.getParameter("page");
        if (pageFromRequest != null) {
            try {
                page = Integer.parseInt(pageFromRequest);
            } catch (NumberFormatException e) {
                System.out.println("非法的 page 值（非整数）：" + pageFromRequest);
            }
            if (page < 1) {
                System.out.println("非法的 page 值（小于 1）：" + pageFromRequest);
                page = 1;
            }
        }

        int count = Integer.parseInt(req.getServletContext().getAttribute("defaultPerPageCount").toString());;
        String countFromRequest = req.getParameter("count");
        if (countFromRequest != null) {
            try {
                count = Integer.parseInt(countFromRequest);
            } catch (NumberFormatException e) {
                System.out.println("非法的 count 值（非整数）：" + countFromRequest);
            }
            if (count > 50) {
                System.out.println("非法的 count 值（大于 50）：" + countFromRequest);
                count = 50;
            }
        }

        int offset = (page - 1) * count;

        String sql = "select id, name, email from user order by id desc limit ?, ?";
        String searchString = req.getParameter("name");
        if (searchString != null && !searchString.trim().isEmpty()) {
            sql = "select id, name, email from user where name like ? order by id desc limit ?, ?";
        }
        Connection connection = MyDBUtil.getConnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);

            if (searchString != null && !searchString.trim().isEmpty()) {
                preparedStatement.setString(1, "%" + searchString + "%");
                preparedStatement.setInt(2, offset);
                preparedStatement.setInt(3, count);
                req.setAttribute("searchString", searchString);
            } else {
                preparedStatement.setInt(1, offset);
                preparedStatement.setInt(2, count);
            }

            ResultSet rs = preparedStatement.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                User user = new User(id, name, email);
                users.add(user);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        // 传递给 jsp (视图)
        req.setAttribute("users", users);
        req.setAttribute("page", page);

        req.getRequestDispatcher("/WEB-INF/users.jsp").forward(req, resp);
    }
}